(function(window) {
  'use strict';

  var ns = window.beneath = window.beneath || {};
  
  function Paper(game) {
    var texts = [];
    var locked = false;
    var paper = game.add.group();

    var sizeFactor = 1.0;

    var y = 30;

    var spr = paper.create(0, 0, 'paper', 2);

    spr.texture.baseTexture.scaleMode = 1;
    var scale = Math.min(game.world.width, game.world.height) / Math.max(spr.width, spr.height) * 0.95;
    spr.width *= scale;
    spr.height *= scale;
    spr.useHandCursor = true;

    sizeFactor = game.world.height / 668;




    paper.x =  -spr.width - 10;
    paper.rotation = -1;

    function releaseLock() {
      locked = false;
    }
    function lock() {
      locked = true;
    }

    this.addHeader = function (text, clickFn) {
      var ret = null;
      if(text.length !== 0) {
        ret = paper.add(game.add.bitmapText(50, y, 'font_black', text, 48 * sizeFactor | 0));
        texts.push({
          spr: ret,
          onClick : clickFn
        });

      }
      y += 80 * sizeFactor | 0;

      return ret;
    };

    this.addText = function (text, clickFn) {
      var ret = null;
      if(text.length !== 0) {
        ret = paper.add(game.add.bitmapText(50, y, 'font_black', text, 28 * sizeFactor | 0));
        texts.push({
          spr: ret,
          onClick : clickFn
        });
      }
      y += 40 * sizeFactor | 0;

      return ret;
    };

    this.addSmallText = function (text, clickFn) {
      var ret = null;
      if(text.length !== 0) {
        ret = paper.add(game.add.bitmapText(50, y, 'font_black', text, 14 * sizeFactor | 0));
        texts.push({
          spr: ret,
          onClick : clickFn
        });
      }
      y += 20 * sizeFactor | 0;

      return ret;
    };

    this.addMediumText = function (text, clickFn) {
      var ret = null;
      if(text.length !== 0) {
        ret = paper.add(game.add.bitmapText(50, y, 'font_black', text, 22 * sizeFactor | 0));
        texts.push({
          spr: ret,
          onClick : clickFn
        });
      }
      y += 30 * sizeFactor | 0;

      return ret;
    };

    this.show = function() {
      if(locked) {
        return;
      }
      var tween = game.add.tween(paper).to({
        x : game.world.centerX - spr.width / 2 - 10,
        rotation : 0
      }, 500, Phaser.Easing.Quadratic.InOut)
      .start();
      tween.onStart.add(lock);
      tween.onComplete.add(releaseLock);
    };

    this.hide = function (done) {
      done = done || function () {};
      if(_.isFunction(done)) {
        done = [done];
      }

      if(locked) {
        return;
      }
      var tween = game.add.tween(paper).to({
        x : game.world.width + 100
      }, 500, Phaser.Easing.Quadratic.InOut)
      .start();
      tween.onStart.add(lock);
      tween.onComplete.add(function () {
        releaseLock();
        for (var i = done.length - 1; i >= 0; i--) {
          done[i]();
        }
      });

    };

    this.updateInput = function () {
      if(locked) {
        return;
      }

      if(!game.input.mousePointer.isDown) {
        return;
      }
      for (var i = texts.length - 1; i >= 0; i--) {
        var t = texts[i];
        if(t.onClick === undefined) {
          continue;
        }
        var x = t.spr.x + paper.x;
        var y = t.spr.y + paper.y;

        var rect = new Phaser.Rectangle(x, y, x + t.spr.textWidth, y + t.spr.textHeight);
        if(Phaser.Rectangle.contains(rect, game.input.x, game.input.y)) {
          t.onClick(t.spr);
        }
      }
    };

    this.destroy = function () {
      paper.destroy();
    };

  }

  function Expenses(game) {
    var chosen = false;
    var paper = this.paper = new Paper(game);
    var totalExpenses = game.state.maintainance + game.state.employees.length * game.state.employeeSalery;
    this.paper.show();
    this.paper.addHeader('Balance');
    this.paper.addMediumText('Maintainance: ');
    this.paper.addSmallText(game.state.maintainance + ' $');
    this.paper.addMediumText('Salaries: ');
    this.paper.addSmallText(game.state.employeeSalery * game.state.employees.length + ' $');
    this.paper.addMediumText('Income: ');
    this.paper.addSmallText(game.state.earned + ' $');
    this.paper.addMediumText('Result: ');
    this.paper.addSmallText( (game.state.earned - totalExpenses) + ' $');
    this.paper.addText('');
    this.paper.addText('Ok [ ]', function (text) {
      if(chosen) {
        return;
      }
      text.text = 'Ok [X]';
      chosen = true;
      setTimeout(function(){
        paper.hide([game.doneFn, function () {
          game.state.money += game.state.earned;
          game.state.money -= totalExpenses;
        }]);
      }, 500);
    });
  }

  function MinersDied (game) {
    var chosen = false;

    var paper = this.paper = new Paper(game);
    this.paper.show();
    this.paper.addText('Workers dead');
    this.paper.addSmallText('Some of your workers were');
    this.paper.addSmallText('caught in a collapsing cave.');
    this.paper.addText('');
    this.paper.addText('Okay [ ]', function (text) {
      if(chosen) {
        return;
      }
      text.text = 'Okay [X]';
      chosen = true;

      _.each(game.employees, function (e) {
        e.morale -= 25;
      });

      setTimeout(function(){
        paper.hide([game.doneFn]);
      }, 500);
    });   
  }

  function IncreaseWage(game, onIgnore, onAccept, onDone) {
    var chosen = false;
    var increase = 50 * (1 + Math.random() * 8 | 0);

    var paper = this.paper = new Paper(game);
    this.paper.show();
    this.paper.addHeader('Notice');
    this.paper.addText('Your worker demand');
    this.paper.addText('a higher wage!');
    this.paper.addText('');
    this.paper.addText('They propose');
    this.paper.addText((game.state.employeeSalery + increase) + '$ / day');
    this.paper.addText('');
    this.paper.addText('Ignore [ ]', function (text) {
      if(chosen) {
        return;
      }
      text.text = 'Ignore [X]';
      chosen = true;


      setTimeout(function(){
        paper.hide([onIgnore, onDone]);
      }, 500);
    });
    this.paper.addSmallText('(Ignoring will decrease morale)');
    this.paper.addText('');
    this.paper.addText('Accept [ ]', function (text) {
      if(chosen) {
        return;
      }
      text.text = 'Accept [X]';
      chosen = true;
      setTimeout(function(){
        paper.hide([function () {
          onAccept(increase);
        }, onDone]);
      }, 500);
    });
  }

  function HelpLocalPolitician(game) {
    var chosen = false;
    var money = (1000 + Math.random() * 1000 | 0);
    var paper = this.paper = new Paper(game);
    this.paper.show();
    this.paper.addHeader('Request');
    this.paper.addText('A local politician');
    this.paper.addText('needs funding.');
    this.paper.addText('If you help him');
    this.paper.addText('he promises to');
    this.paper.addText('return the favor');
    this.paper.addText('some day.');
    this.paper.addText('He requests ' + money + '$');
    this.paper.addText('');
    this.paper.addText('Don\'t help [ ]', function (text) {
      if(chosen) {
        return;
      }
      text.text = 'Don\'t help [X]';
      chosen = true;
      setTimeout(function(){
        paper.hide(game.doneFn);
      }, 500);
    });
    this.paper.addText('');
    if(game.state.money >= money) {

      this.paper.addText('Help [ ]', function (text) {
        if(chosen) {
          return;
        }
        text.text = 'Help [X]';
        chosen = true;
        game.state.money -= money;
        game.state.favors += 1;
        setTimeout(function(){
          paper.hide(game.doneFn);
        }, 500);
      });
    } else {
      this.paper.addText('you can\'t afford');
      this.paper.addText('to help him..');
    }
  }

  function SectorProblems(game) {
    var chosen = false;
    var increase = (1 + Math.random() * 2 | 0) * 50;
    game.state.maintainance += increase;
    var paper = this.paper = new Paper(game);
    this.paper.show();
    this.paper.addHeader('Report');
    this.paper.addSmallText('Your geologist informs you');
    this.paper.addSmallText('that todays mining section is really unstable');
    this.paper.addSmallText('and could collapse, if you started mining.');
    this.paper.addSmallText('');
    this.paper.addSmallText('He suggests you find a better section to mine');
    this.paper.addSmallText('this will take a day.');
    this.paper.addSmallText('');
    this.paper.addSmallText('Find better place to mine [ ]', function (text) {
      if(chosen)return;
      chosen = true;
      game.state.skipDay = true;
      text.text = 'Find better place to mine [X]';
      setTimeout(function(){
        paper.hide(game.doneFn);
      }, 500);
    });
    this.paper.addSmallText('Ignore advice [ ]', function (text) {
      if(chosen)return;
      chosen = true;
      game.state.unstableArea = true;
      text.text = 'Ignore advice [X]';
      setTimeout(function(){
        paper.hide(game.doneFn);
      }, 500);
    });
  }

  function MaintainanceCost1(game) {
    var chosen = false;
    var increase = (1 + Math.random() * 2 | 0) * 50;
    game.state.maintainance += increase;
    var paper = this.paper = new Paper(game);
    this.paper.show();
    this.paper.addHeader('Report');
    this.paper.addSmallText('The supply of cleaning');
    this.paper.addSmallText('liquid has dropped');
    this.paper.addSmallText('Maintainance cost increased');
    this.paper.addSmallText('');
    this.paper.addSmallText('Cost is now ' + (game.state.maintainance) + '$');
    this.paper.addSmallText('');
    this.paper.addSmallText('Ok [ ]', function (text) {
      if(chosen)return;
      chosen = true;
      text.text = 'Ok [X]';
      setTimeout(function(){
        paper.hide(game.doneFn);
      }, 500);
    });
  }

  function FormedUnion(game, who) {
    var chosen = false;
    var paper = this.paper = new Paper(game);
    this.paper.show();
    this.paper.addHeader('Note');
    this.paper.addSmallText(who.name + ' has formed a union');
    this.paper.addSmallText('This means they can now make demands');
    this.paper.addSmallText('as a whole.');
    this.paper.addSmallText('');



    this.paper.addSmallText('Ok [ ]', function (text) {
      if(chosen)return;
      chosen = true;
      game.state.haveUnion = true;
      who.unionLeader = true;
      text.text = 'Ok [X]';
      setTimeout(function(){
        paper.hide(game.doneFn);
      }, 500);
    });
    
    if(game.state.favors >= 3) {
      this.paper.addSmallText('');
      this.paper.addSmallText('I can call in a lot of favors');
      this.paper.addSmallText('and neutralize their union.');
      this.paper.addSmallText('');
      this.paper.addSmallText('Call in favors [ ]', function (text) {
      if(chosen)return;
        chosen = true;
        text.text = 'Call in favors [X]';
        setTimeout(function(){
          paper.hide(game.doneFn);
        }, 500);
      });
    }
  }
  function UnionMaxCommandsDemand(game) {
    var chosen = false;
    var maxCommands = 0;
    if(game.state.maxCommands > 15) {
      maxCommands = 15;
    } else if (game.state.maxCommands > 10) {
      maxCommands = 10;
    } else if (game.state.maxCommands > 5) {
      maxCommands = 5;
    } else if (game.state.maxCommands >= 0) {
      maxCommands = 0;
    }

    var paper = this.paper = new Paper(game);
    this.paper.show();
    this.paper.addHeader('Union Policy');
    if(maxCommands !== 0) {
      this.paper.addSmallText('Union members are to only follow');
      this.paper.addSmallText(maxCommands + ' orders each day.');
    } else {
      this.paper.addSmallText('Union members are no longer to follow orders.');
    }
    this.paper.addSmallText('');
    this.paper.addSmallText('Ok [ ]', function (text) {
      if(chosen)return;
      chosen = true;
      game.state.maxCommands = maxCommands;
      text.text = 'Ok [X]';
      setTimeout(function(){
        paper.hide(game.doneFn);
      }, 500);
    });
  }
  function UnionDisbanded(game) {
    var paper = this.paper = new Paper(game);
    this.paper.show();
    this.paper.addHeader('Note');
    this.paper.addSmallText('There is no longer a union leader');
    this.paper.addSmallText('the miner union has disbanded.');

    this.paper.addSmallText('');
    this.paper.addSmallText('Ok [ ]', function (text) {
      if(chosen)return;
      chosen = true;
      game.state.haveUnion = false;
      game.state.maxCommands = 99999;
      text.text = 'Ok [X]';
      setTimeout(function(){
        paper.hide(game.doneFn);
      }, 500);
    });
  }

  function MaintainanceCost2(game) {
    var chosen = false;
    var increase = (2 + Math.random() * 4 | 0) * 25;
    game.state.maintainance += increase;
    var paper = this.paper = new Paper(game);
    this.paper.show();
    this.paper.addHeader('Report');
    this.paper.addSmallText('The supply of hammers');
    this.paper.addSmallText('has fallen because');
    this.paper.addSmallText('of a forrest fire in china.');
    this.paper.addSmallText('Suppliers have');
    this.paper.addSmallText('raised their prices.');
    this.paper.addSmallText('Maintainance cost increased.');
    this.paper.addSmallText('');
    this.paper.addSmallText('Cost is now ' + (game.state.maintainance) + '$');
    this.paper.addSmallText('');
    this.paper.addSmallText('Ok [ ]', function (text) {
      if(chosen)return;
      chosen = true;
      text.text = 'Ok [X]';
      setTimeout(function(){
        paper.hide(game.doneFn);
      }, 500);
    });
  }

  function Politics(game) {
    var chosen = false;
    var increase = (2 + Math.random() * 4 | 0) * 50;
    game.state.maintainance += increase;
    var paper = this.paper = new Paper(game);
    this.paper.show();
    this.paper.addHeader('Report');
    this.paper.addSmallText('The local commitee');
    this.paper.addSmallText('has decided that coal mine workers');
    this.paper.addSmallText('need a much higher minimum wage');
    this.paper.addSmallText('and have therefore, mandated that you');
    this.paper.addSmallText('must raise your wage to');
    this.paper.addSmallText((game.state.employeeSalery + increase) + '$');
    this.paper.addSmallText('');
    this.paper.addSmallText('Ok [ ]', function (text) {
      if(chosen)return;
      text.text = 'Ok [X]';
      chosen = true;
      game.state.employeeSalery += increase;
      setTimeout(function(){
        paper.hide(game.doneFn);
      }, 500);
    });
    if(game.state.favors >= 1) {
      this.paper.addSmallText('');
      this.paper.addSmallText('Make use of political favors [ ]', function (text) {
        if(chosen)return;
        chosen = true;
        text.text = 'Make use of political favors [X]';
        game.state.favors -= 1;
        setTimeout(function(){
          paper.hide(game.doneFn);
        }, 500);
      });
    }

    var bribeCost = 5000 + (Math.random() * 8 | 0) * 250;

    if(game.state.money >= bribeCost) {
      this.paper.addSmallText('');
      this.paper.addSmallText('You happen to know some members');
      this.paper.addSmallText('of this commitee and you could');
      this.paper.addSmallText('bribe them with ' + bribeCost + ' $');
      this.paper.addSmallText('Your employees will ');
      this.paper.addSmallText('probably not like this..');
      this.paper.addSmallText('');
      this.paper.addSmallText('Bribe commitee members [ ]', function (text) {
        if(chosen)return;
        chosen = true;
        text.text = 'Bribe commitee members [X]';
        game.state.money -= bribeCost;
        _.each(game.state.employees, function (e) {
          e.morale -= 25;
        });
        setTimeout(function(){
          paper.hide(game.doneFn);
        }, 500);
      });
    }
  }

  function Environment(game) {
    var chosen = false;
    var increase = (3 + Math.random() * 5 | 0) * 50;
    game.state.maintainance += increase;
    var paper = this.paper = new Paper(game);
    this.paper.show();
    this.paper.addHeader('Report');
    this.paper.addSmallText('Environmentalist');
    this.paper.addSmallText('Have convinced government that');
    this.paper.addSmallText('new eco freindly mining techniques are needed.');
    this.paper.addSmallText('');
    this.paper.addSmallText('This will raise your maintainance cost to');
    this.paper.addSmallText((game.state.maintainance + increase) + '$');
    this.paper.addSmallText('');
    this.paper.addSmallText('Ok [ ]', function (text) {
      if(chosen)return;
      chosen = true;
      text.text = 'Ok [X]';
      game.state.maintainance += increase;
      setTimeout(function(){
        paper.hide(game.doneFn);
      }, 500);
    });
    if(game.state.favors >= 1) {
      this.paper.addSmallText('');
      this.paper.addSmallText('Make use of political favors [ ]', function (text) {
        if(chosen)return;
        chosen = true;
        text.text = 'Make use of political favors [X]';
        game.state.favors -= 1;
        setTimeout(function(){
          paper.hide(game.doneFn);
        }, 500);
      });
    }
    var bribeCost = 5000 + (Math.random() * 8 | 0) * 250;

    if(game.state.money >= bribeCost) {
      this.paper.addSmallText('');
      this.paper.addSmallText('Using some political connections');
      this.paper.addSmallText('you know a few people who can extempt');
      this.paper.addSmallText('your bussiness from havin to follow ');
      this.paper.addSmallText('theese pointless regulations. ');
      this.paper.addSmallText('It would cost ' + bribeCost + '$ to do so.');
      this.paper.addSmallText('');
      this.paper.addSmallText('Bribe politicians [ ]', function (text) {
        if(chosen)return;
        chosen = true;
        text.text = 'Bribe politicians [X]';
        game.state.money -= bribeCost;
        setTimeout(function(){
          paper.hide(game.doneFn);
        }, 500);
      });
    }
  }

  function BetterEquipmentAvailable(game, onIgnore, onAccept, onDone) {
    var chosen = false;
    var cost = (500 + Math.random() * 5000 | 0);
    var paper = this.paper = new Paper(game);
    this.paper.show();
    this.paper.addHeader('Equipment');
    this.paper.addText('You got a special');
    this.paper.addText('offer on new mining');
    this.paper.addText('equipment.');
    this.paper.addText('');
    this.paper.addText('Cost ' + cost + '$');
    this.paper.addText('');
    this.paper.addText('Ignore [ ]', function (text) {
      if(chosen) {
        return;
      }
      text.text = 'Ignore [X]';
      chosen = true;

      setTimeout(function(){
        paper.hide([onIgnore, onDone]);
      }, 500);
    });
    this.paper.addText('');
    this.paper.addText('Buy [ ]', function (text) {
      if(chosen) {
        return;
      }
      text.text = 'Buy [X]';
      chosen = true;
      setTimeout(function(){
        paper.hide([function () {
          onAccept(cost);
        }, onDone]);
      }, 500);
    });
  }
  function Resign(game, onAccept, onDone, stats) {
    var chosen = false;
    var paper = this.paper = new Paper(game);
    this.paper.show();
    this.paper.addHeader('I quit!');
    if(stats.morale < 25) {
      this.paper.addMediumText('I hate working here');   
    }
    this.paper.addMediumText('- ' + stats.name);

    this.paper.addText('');
    this.paper.addText('OK [ ]', function (text) {
      if(chosen) {
        return;
      }
      text.text = 'OK [X]';
      chosen = true;
      setTimeout(function(){
        paper.hide([onAccept, onDone]);
      }, 500);
    });
  }

  function BetterEquipmentDemand(game, onAccept, onDone, stats) {
    var chosen = false;
    var paper = this.paper = new Paper(game);
    this.paper.show();
    this.paper.addHeader('I quit!');
    if(stats.morale < 25) {
      this.paper.addText('I hate working here');   
    }
    this.paper.addHeader('- ' + stats.name);

    this.paper.addText('');
    this.paper.addText('OK [ ]', function (text) {
      if(chosen) {
        return;
      }
      text.text = 'OK [X]';
      chosen = true;
      setTimeout(function(){
        paper.hide([onIgnore, onDone]);
      }, 500);
    });
  }

  

  function ApplicationCV(game, onIgnore, onAccept, onDone, stats) {
    var chosen = false;
    var paper = this.paper = new Paper(game);
    this.paper.show();
    this.paper.addHeader('Application');
    this.paper.addText('Name: ' + stats.name);
    this.paper.addText('Age: ' + stats.age);
    this.paper.addText('Experience: ');
    this.paper.addSmallText(stats.experience);
    this.paper.addText('About me: ');
    this.paper.addSmallText(stats.personality.about);
    this.paper.addText('');
    this.paper.addText('Ignore [ ]', function (text) {
      if(chosen) {
        return;
      }
      text.text = 'Ignore [X]';
      chosen = true;

      setTimeout(function(){
        paper.hide([onIgnore, onDone]);
      }, 500);
    });
    this.paper.addText('');
    this.paper.addText('Hire [ ]', function (text) {
      if(chosen) {
        return;
      }
      text.text = 'Hire [X]';
      chosen = true;
      setTimeout(function(){
        paper.hide([onAccept, onDone]);
      }, 500);
    });
  }

  function StartNote1(game, onDone) {
    var chosen = false;
    var paper = this.paper = new Paper(game);
    this.paper.show();
    this.paper.addHeader('Welcome');
    this.paper.addSmallText('This game was made for');
    this.paper.addSmallText('ludum dare in 48 hours.');
    this.paper.addSmallText('');
    this.paper.addSmallText('You are a coal shaft manager');
    this.paper.addSmallText('your job is to make the hard decisions,');
    this.paper.addSmallText('and make sure your little coal mine');
    this.paper.addSmallText('does not bankrupt.');
    this.paper.addSmallText('');
    this.paper.addSmallText('You loose the game when you');
    this.paper.addSmallText('cannot pay your bills.');
    this.paper.addSmallText('');
    this.paper.addSmallText('This screen is the \'office\' screen.');
    this.paper.addSmallText('This is where you take all. But because');
    this.paper.addSmallText('This is the first day, there is nothing');
    this.paper.addSmallText('to decide.');

    this.paper.addSmallText('');
    this.paper.addMediumText('Do you understand? [ ]', function (text) {
      if(chosen) {
        return;
      }
      text.text = 'Do you understand? [X]';
      chosen = true;
      setTimeout(function(){
        paper.hide(onDone);
      }, 500);
    });
    this.paper.addSmallText('(Click above to proceed)');
  }
  function StartNote2(game, onDone) {
    var chosen = false;
    var paper = this.paper = new Paper(game);
    this.paper.show();
    this.paper.addHeader('More Info');
    this.paper.addSmallText('Your employees are your');
    this.paper.addSmallText('most important freinds and your');
    this.paper.addSmallText('biggest enemies. They will form unions,');
    this.paper.addSmallText('conspire to demand more pay');
    this.paper.addSmallText('and demand expensive equipment.');
    this.paper.addSmallText('');
    this.paper.addSmallText('You can ofcourse ignore demands');
    this.paper.addSmallText('but this will lower morales, and');
    this.paper.addSmallText('lower morals mean less work done.');
    this.paper.addSmallText('');
    this.paper.addSmallText('You can order your workers around by');
    this.paper.addSmallText('dragging them around. This will lower');
    this.paper.addSmallText('morales too, but can be very usefull.');
    this.paper.addSmallText('');
    this.paper.addSmallText('The right decisions and day to day');
    this.paper.addSmallText('micromanagement is key to success.');
    this.paper.addSmallText('');
    this.paper.addMediumText('Start game [ ]', function (text) {
      if(chosen) {
        return;
      }
      text.text = 'Start game [X]';
      chosen = true;
      setTimeout(function(){
        paper.hide(onDone);
      }, 500);
    });
    this.paper.addSmallText('(Click above to start the first day)');

  }
  function nullFn() {}
  function createDecision(game, state) {
    var chances = [];

    if(Math.random() < 0.1 || state.employees.length <= 2){
      chances.push({
        paper : function paperFn(){
          var applicant = ns.Miner.randomMiner();
          return new ApplicationCV(game, nullFn, function hireFn() {
            state.employees.push(applicant);
          }, game.doneFn, applicant);

        }
      });
    }

    var resigner = null;
    _.find(state.employees, function eachFn(who) {
      if(!who.unionLeader && (who.morale < 15) && (Math.random() < 0.1) && !who.resigned) {

        who.resigned = true;
        resigner = {
          paper : function paperFn() {
            return new Resign(game, function hireFn() {

              var employees = [];

              for (var i = state.employees.length - 1; i >= 0; i--) {
                var emp = state.employees[i];
                if(emp.name === who.name) {
                  continue;
                }
                employees.push(emp);
              }
              state.employees = employees;

              }, game.doneFn, who);
          }
        };
        return true;
      }
    });

    if(resigner) {
      chances.push(resigner);
    }



    


    return _.sample(chances);
  }

  function createDecisionList(game, state) {

    if(state.day === 0) {
      return [{
        paper : function paperFn() {
          return new StartNote1(game, game.doneFn);
        }
      }, 
      {
        paper : function paperFn() {
          return new StartNote2(game, game.doneFn);
        }
      }];
    }
    var out = [];

    if(game.state.minerDied.length !== 0) {
      out.push({
        paper : function () {
          return new MinersDied(game);
        }
      });
    }
    if(game.state.haveUnion === true && _.any(game.state.employees, function (emp) {
      return emp.unionLeader === true;
    }) === false){
      out.push({
        paper : function () {
          return new UnionDisbanded(game);
        }
      });
    }

    if(Math.random() < 0.5) {
      out.push({
        paper : function paperFn(){
          return new BetterEquipmentAvailable(game, nullFn, function (cost) {
            state.money -= cost;

            _.each(state.employee, function(e){
              e.speed += 0.1 + Math.random() * 0.2;
              e.morale += 5 + Math.random() * 10;
            });
          }, game.doneFn); 
        }
      });
    }

    var wage = null;
    _.find(state.employees, function (e) {
      if(e.ideas.indexOf('wage') !== -1 && Math.random() < 0.2) {
        wage = {
          paper : function () {
            return new IncreaseWage(game, function noIncrease() {
              e.morale -= 25 * Math.random();
              _.each(state.employees, function (ee) {
                if(e === ee || Math.random() < 0.5) {
                  return;
                }
                ee.morale -= Math.random() * 30;
              });
            }, function increaseWages(increase) {
              e.morale += 25;
              state.employeeSalery += increase;
              _.each(state.employees, function (ee) {
                if(e === ee || Math.random() < 0.5) {
                  return;
                }
                ee.morale += Math.random() * 30;
              });
            }, game.doneFn);
          }
        };
        return true;
      } 
    });
    if(wage) {
      out.push(wage);
    }

    var union = null;
    
    if(!state.haveUnion){
      _.find(state.employees, function (e) {
        if(e.ideas.indexOf('union') !== -1 && Math.random() < 0.2) {
          union = {
            paper : function () {
              return new FormedUnion(game, e);
            }
          };
          return true;
        } 
      });
      if(union) {
        out.push(union);
      }
    }

    var randomEvents = [
      [_.sample([MaintainanceCost1, MaintainanceCost2]), 0.2],
      [HelpLocalPolitician, 0.25],
      [Politics, 0.2],
      [Environment, 0.2],
      [SectorProblems, 0.2]];

    _.each(randomEvents, function (e) {
      if(e[1] > Math.random()){
        out.push({
          paper : function () {
            return new e[0](game);
          }
        });
      }
      
    });

    var randomUnionEvents = [
      [UnionMaxCommandsDemand, 0.25]
    ];

    if(game.state.haveUnion === true) {
      _.each(randomEvents, function (e) {
        if(e[1] < Math.random()) return;
        out.push({
          paper : function () {
            return new e[0](game);
          }
        });
      });
    }




    // Between 2 and 5 things can happend
    for(var i = 0 ; i < 2 + Math.random() * 3 | 0 ; i ++){
      var decision = createDecision(game, state);
      if(decision) {
        out.push(decision);
      }
    }
    return _.filter(out, function () {
      return out !== null;
    });
  }

  function Office() {
    
  }

  Office.prototype = {
    init : function (state) {
      this.state = state[0];
      this.state.skipDay = false;
      this.state.unstableArea = false;
      this.state.striking = false;
    },
    create: function () {
      var self = this;
      this.paper = null;
      if(this.state.money < 0) {
        this.game.state.start('gameover', true, false, [this.state]);
        return;
      }


      _.each(this.state.employees, function (e) {
        e.ideas = _.unique(e.ideas);
      });


      this.list = createDecisionList(this, this.state);
      if(this.state.day !== 0) {
        this.list = [{
          paper : function () {
            return new Expenses(self);
          }
        }].concat(this.list);
      }
      console.log(this.list);
      this.listId = 0;

      this.doneFn = function doneFn(){
        
        self.listId += 1;
        if(self.paper !== null) {
          self.paper.paper.destroy();
        }

        if(self.listId >= self.list.length) {
          self.nextDay();        
        } else {
          self.paper = self.list[self.listId].paper();
        }
      };


      this.moneyDisplayText = this.add.bitmapText(0,0, 'font','money: ' + this.state.money, 32);

      this.moneyDisplayText.x = this.world.width - this.moneyDisplayText.textWidth - 20;
      this.moneyDisplayText.y = 20;

      if(this.list.length === 0) {
        this.nextDay();
        return;
      }

      this.paper = this.list[0].paper();

    },
    update: function () {
      if(this.paper === null) {
        return;
      }
      this.paper.paper.updateInput();

      this.moneyDisplayText.text = 'money: ' + this.state.money + '$';
      this.moneyDisplayText.x = this.world.width - this.moneyDisplayText.textWidth - 20;
      this.moneyDisplayText.y = 20;
    },
    nextDay : function() {
      this.paper = null;
      var self = this;

      var tween = this.add.tween(this.moneyDisplayText)
        .to({
          x : this.world.width
        }, 250, Phaser.Easing.Quadratic.InOut)
        .start()
        .onComplete.add(function () {
          this.state.day += 1;
          this.state.coal = [];
          this.state.minerDied = [];
          this.state.earned = 0;
          if(this.state.skipDay === true) {
            
            var text = this.add.bitmapText(0, this.world.height + 50, 'font', 'Finding better place to mine');
            text.x = this.world.centerX - text.textWidth / 2;

            this.add.tween(text).to({y : this.world.centerY}, 500, Phaser.Easing.Quadratic.InOut)
                                .to({y : this.world.centerY}, 750, Phaser.Easing.Quadratic.InOut)
                                .to({y : this.world.height + 50}, 500, Phaser.Easing.Quadratic.InOut)
                                .start();
            setTimeout(function () {
              self.game.state.start('office', true, false, [self.state]);
            }, 1750);




          } else if (this.state.employees.length === 0) {

            var text2 = this.add.bitmapText(0, this.world.height + 50, 'font', 'You do not have any employees.. Skipping day.');
            this.state.haveUnion = false;
            text2.x = this.world.centerX - text2.textWidth / 2;
            this.add.tween(text2).to({y : this.world.centerY}, 500, Phaser.Easing.Quadratic.InOut)
                                .to({y : this.world.centerY}, 750, Phaser.Easing.Quadratic.InOut)
                                .to({y : this.world.height + 50}, 500, Phaser.Easing.Quadratic.InOut)
                                .start();
            setTimeout(function () {
              self.game.state.start('office', true, false, [self.state]);
            }, 1750);
          } else if (this.state.striking === true) {

            var text3 = this.add.bitmapText(0, this.world.height + 50, 'font', 'Your employees are on strike..');
            text3.x = this.world.centerX - text3.textWidth / 2;
            this.add.tween(text3).to({y : this.world.centerY}, 500, Phaser.Easing.Quadratic.InOut)
                                .to({y : this.world.centerY}, 750, Phaser.Easing.Quadratic.InOut)
                                .to({y : this.world.height + 50}, 500, Phaser.Easing.Quadratic.InOut)
                                .start();
            setTimeout(function () {
              self.game.state.start('office', true, false, [self.state]);
            }, 1750);
          } else {
            this.game.state.start('game', true, false, [this.state]);
          }
        }, this);
    }
  };
  window.beneath.Office = Office;



})(window);
